"use client";

import { useState, useEffect } from "react";
import { useLanguage } from "@/contexts/LanguageContext";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Trash2 } from "lucide-react";

export function StudentList() {
  const [students, setStudents] = useState<string[]>([]);
  const [newStudent, setNewStudent] = useState("");
  const { t } = useLanguage();

  useEffect(() => {
    const initialStudents = ["James", "Michael", "David", "William", "Robert"];
    setStudents(initialStudents);
    localStorage.setItem("students", JSON.stringify(initialStudents));
  }, []);

  const addStudent = () => {
    if (newStudent.trim()) {
      const updatedStudents = [...students, newStudent.trim()];
      setStudents(updatedStudents);
      localStorage.setItem("students", JSON.stringify(updatedStudents));
      setNewStudent("");
    }
  };

  const deleteStudent = (index: number) => {
    const updatedStudents = students.filter((_, i) => i !== index);
    setStudents(updatedStudents);
    localStorage.setItem("students", JSON.stringify(updatedStudents));
  };

  const exportData = () => {
    const dataStr = JSON.stringify(students);
    const dataUri =
      "data:application/json;charset=utf-8," + encodeURIComponent(dataStr);
    const exportFileDefaultName = "student-list.json";
    const linkElement = document.createElement("a");
    linkElement.setAttribute("href", dataUri);
    linkElement.setAttribute("download", exportFileDefaultName);
    linkElement.click();
  };

  const importData = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result;
        if (typeof content === "string") {
          const importedStudents = JSON.parse(content);
          setStudents(importedStudents);
          localStorage.setItem("students", JSON.stringify(importedStudents));
        }
      };
      reader.readAsText(file);
    }
  };

  return (
    <div>
      <h2 className="text-2xl font-bold mb-4">{t("同学列表")}</h2>
      <div className="flex justify-end space-x-2 mb-4">
        <Button onClick={exportData}>{t("导出")}</Button>
        <label htmlFor="import-file" className="cursor-pointer">
          <Input
            id="import-file"
            type="file"
            className="hidden"
            onChange={importData}
            accept=".json"
          />
          <Button>{t("导入")}</Button>
        </label>
      </div>
      <div className="flex space-x-2 mb-4">
        <Input
          type="text"
          value={newStudent}
          onChange={(e) => setNewStudent(e.target.value)}
          placeholder={t("输入同学姓名")}
        />
        <Button onClick={addStudent}>{t("添加")}</Button>
      </div>
      <ul className="space-y-2">
        {students.map((student, index) => (
          <li
            key={index}
            className="flex items-center justify-between bg-white p-2 rounded"
          >
            <span>{student}</span>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => deleteStudent(index)}
            >
              <Trash2 className="h-4 w-4" />
            </Button>
          </li>
        ))}
      </ul>
    </div>
  );
}
